package com.berchen.阻塞与非阻塞;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Scanner;

public class TestNonBlock1 {

    @Test
    public void send() throws IOException {
        DatagramChannel dc = DatagramChannel.open();
        dc.configureBlocking(false);    // 切换成非阻塞模式

        ByteBuffer buf = ByteBuffer.allocate(1024);

        Scanner sc=new Scanner(System.in);

        while (sc.hasNext()){

            String str=sc.next();
            buf.put((LocalDateTime.now().toString()+str).getBytes());
            buf.flip();
            dc.send(buf,new InetSocketAddress("127.0.0.1",10002));
            buf.clear();
        }

        sc.close();
    }
    @Test
    public void receive() throws IOException {

        DatagramChannel dc = DatagramChannel.open();
        dc.configureBlocking(false);
        dc.bind(new InetSocketAddress(10002));

        Selector selector=Selector.open();

        dc.register(selector, SelectionKey.OP_READ);

        while (selector.select()>0){

            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while(it.hasNext()){

                SelectionKey s = it.next();
                if(s.isReadable()){
                    ByteBuffer buf = ByteBuffer.allocate(1024);
                    dc.receive(buf);

                    System.out.println(new String(buf.array(),0,buf.limit()));
                }
            }
            it.remove();
        }

    }
}
